//
//  PlayScenicVC.swift
//  ImGuider X
//
//  Created by 王鹏宇 on 10/8/18.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit
import FSPagerView

class PlayScenicVC: BasePlayVC,PlayBarDelegate,SearchNumVCDelegate {
    
    @IBOutlet weak var bgView: UIView!
    
    @IBOutlet weak var foldView: UIView!
    @IBOutlet weak var menuView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var foldBtn: UIButton!
    @IBOutlet weak var playView: UIView!
    @IBOutlet weak var foldViewHeight: NSLayoutConstraint!
    
    @IBOutlet weak var collectionHeight: NSLayoutConstraint!
    var changeMapBtn : UIButton?
    var viewmodel:PlayViewModel = PlayViewModel()
    var dropListView : X_DropListView!
    var pageView : OtherDetailHeadView!
    
    var playBar : PlayBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if !isPlayAlways {
            WPY_AVPlayer.playManager.stop()
        }
        
        self.dropListView.removeFromSuperview()
    }
}


extension PlayScenicVC {
    
    func setupUI() {
        
        self.setNavBarStyle(.translucence)
        
        playBar = PlayBar(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 120))
        playBar.delegate = self
        self.playView.addSubview(playBar)
        
        self.menuView.layer.cornerRadius = 20.0
        self.menuView.clipsToBounds = true
        
        pageView = OtherDetailHeadView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - kTableBarHeight - 102))
        self.bgView.insertSubview(pageView, belowSubview: self.foldView)
        
        pageView.selectIndex = {
            
            [weak self] index in
            guard let `self` = self else { return }
            
            if self.changeMapBtn?.isSelected ?? false {
                
                if let count = self.viewmodel.line?.mapPicArray?.count, count > 0 {
                    
                    self.setupBrowser(images:self.viewmodel.line?.mapPicArray, index: index) { (next) -> UIView? in
                        
                        return  self.pageView
                    }
                }
            }
        }
        pageView.pageControl.snp.remakeConstraints {
            
            [weak self] maker in
            guard let `self` = self else { return }
            
            maker.left.equalToSuperview()
            maker.right.equalToSuperview()
            maker.bottom.equalTo(self.foldBtn.snp.top)
            maker.height.equalTo(30)
        }
        
        self.dropListView = X_DropListView.SetupDropListView(frame: CGRect(x: kScreenWidth - 115, y: kNavigationBarHeight - 15, width: 110, height: 60), typeList: [ListType.LoopBtnType], contentView: self.view) 
        
        self.collectionView.register(UINib(nibName: "RecordCell", bundle: nil), forCellWithReuseIdentifier: "RecordCell")
        
        
        let rightItem = UIBarButtonItem(image: UIImage(named:"more"), style: .plain, target: self, action: #selector(goMore))
        self.navigationItem.rightBarButtonItem = rightItem
    }
    
    func setupMenuView(){
        
        self.menuView.backgroundColor = UIColor.white
        
        let width = kScreenWidth / viewmodel.menuTagsArray.count
        
        for i in 0 ..< viewmodel.menuTagsArray.count {
            
            let btn = UIButton(type: .custom)
            btn.frame = CGRect(x: i * width, y: 0, width: width, height: 60)
            self.menuView.addSubview(btn)
            
            let type = viewmodel.menuTagsArray[i]
            
            switch(type){
                
            case .MenuTypeCamera:
                btn.setImage(UIImage(named: "cameraMenu"), for: .normal)
                btn.addTarget(self, action: #selector(goCamera), for: .touchUpInside)
            case .MenuTypeMap:
                btn.setImage(UIImage(named: "mapMenu"), for: .normal)
                btn.setImage(UIImage(named: "imageMenu"), for: .selected)
                btn.addTarget(self, action: #selector(changeMapModel(sender:)), for: .touchUpInside)
                self.changeMapBtn = btn
            case .MenuTypeSearch:
                btn.setImage(UIImage(named: "searchMenu"), for: .normal)
                btn.addTarget(self, action: #selector(goSearch), for: .touchUpInside)
                
            default:
                break
            }
        }
    }
    
    private func setupData() {
        
        viewmodel.reloadData()
        
        viewmodel.loadFinished = {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            if let errmsg = errmsg {
                
                self.view.makeToast(errmsg)
                
            }
            
            self.collectionView.reloadData()
            self.setupMenuView()
            if let count = self.viewmodel.records?.count , count > 0 {
                WPY_AVPlayer.playManager.musicArray = self.viewmodel.records!
                WPY_AVPlayer.playManager.lineModel = self.viewmodel.line
                
                self.selectCellWithIndex(index: 0, immediately: false)
            }
            
            
        }
        
        viewmodel.reloadRecord = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.pageView.pics = self.viewmodel.currentPics
        }
        
        viewmodel.progressText = {
            
            [weak self] msg in
            guard let `self` = self else { return }
            
            self.playBar.downloadBtn.setTitle(msg, for: .normal)
            self.playBar.downloadBtn.setImage(nil, for: .normal)
        }
        
    }
    
    @IBAction func foldAction(_ sender: UIButton) {
        
        var name = LocalizedString("unfold")
        var flag = false
        
        if sender.isSelected{
            
            name = LocalizedString("unfold")
            self.collectionHeight.constant = 150.0
            self.collectionView.isHidden = false
            sender.isSelected = false
        }else {
            
            name = LocalizedString("fold")
            self.collectionHeight.constant = 0.0
            flag  = true
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.view.layoutIfNeeded()
        }) {
            
            [weak self] _ in
            guard let `self` = self else { return }
            
            if flag == true {
                
                self.collectionView.isHidden = flag
                sender.isSelected = flag
            }
            sender.setImage(UIImage(named:name), for: .normal)
        }
    }
    
    
    func changeScenicPointWithIndex(index : Int){
        
        guard let record = self.viewmodel.records?[index] else {return}
        
        let indexPath = IndexPath(row: index, section: 0)
        
        if let cell = self.collectionView.cellForItem(at: self.viewmodel.currentIndexPath) as? RecordCell {
            cell.isSelect = false
        }
        
        if let currentCell = self.collectionView.cellForItem(at: indexPath) as? RecordCell {
            
            currentCell.isSelect = true
        }
        
        
        self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        
        self.collectionView.reloadData()
        self.viewmodel.currentIndexPath = indexPath
        self.viewmodel.currentRecord = record
    }
    
    
    private func selectCellWithIndex(index : Int,immediately : Bool){
        
        changeScenicPointWithIndex(index: index)
        self.playBar.playMusicWithIndex(index: index, immediately: immediately)
    }
    
    
    // 切换播放调整UI
    func changePointTo(index: Int) {
        
        self.changeScenicPointWithIndex(index: index)
    }
    
    //下载
    func downloadAction() {
        
        viewmodel.downloadTapped()
    }
    
    @objc func goMore(){
        
        if self.dropListView.isHidden {
            self.dropListView.show()
        }else{
            self.dropListView.hidde()
        }
        
    }
    
    @objc func changeMapModel(sender : UIButton){
        
        if !sender.isSelected {
            
            self.pageView.autoScroll = false
            self.pageView.imageContentMode = .scaleAspectFit
            self.pageView.pics = self.viewmodel.line?.mapPicArray
            sender.isSelected = true
            
            
        }else {
            
            self.pageView.autoScroll = true
            self.pageView.imageContentMode = .scaleAspectFill
            self.pageView.pics = self.viewmodel.currentPics
            sender.isSelected = false
        }
        
        
    }
    
    @objc func goCamera(){
        
        self.present(MyCamera(), animated: true, completion: nil)
    }
    
    
    @objc func goSearch(){
        
        self.isPlayAlways = true
        
        WRNavigationBar.defaultNavBarBarTintColor = UIColor.clear
        let searchVC = SearchNumVC()
        searchVC.records = self.viewmodel.records ?? []
        searchVC.delegate = self
        let nav = UINavigationController(rootViewController: searchVC)
        
        self.present(nav, animated: true, completion: nil)
        
        //        self.navigationController?.pushViewController(searchVC, animated: true)
        //        self.present(searchVC, animated: true, completion: nil)
    }
    
    
    func selectTheRecord(record: Record) {
        guard let arr = self.viewmodel.records as NSArray? else{
            return
        }
        let index = arr.index(of: record)
        DispatchQueue.main.after(0.5) {
            self.selectCellWithIndex(index: index, immediately: true)
        }
    }
}

extension PlayScenicVC: FSPagerViewDelegate,FSPagerViewDataSource {
    
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        
        return viewmodel.currentPics?.count ?? 0
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "FSPagerViewCell", at: index)
        cell.imageView?.contentMode = .scaleAspectFill
        
        let pic = viewmodel.currentPics?[index]
        
        cell.imageView?.setImage(string: pic, placeholder: UIImage(named: "placeholder_rec")!)
        
        return cell
    }
}

extension PlayScenicVC: UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewmodel.records?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecordCell", for: indexPath) as! RecordCell
        
        let record = viewmodel.records?[indexPath.row]
        cell.record = record
        cell.isSelect = record == viewmodel.currentRecord
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        if !viewmodel.hasDownload {
            
            return
        }
        
        guard let playpath = viewmodel.line?.records?[indexPath.row].playpath else { return }
        
        let cell = cell as! RecordCell
        
        cell.progressLabel.isHidden = false
        
        viewmodel.cellDownloadText(playpath: playpath) {
            
            [weak cell] proText,playpath2 in
            
            guard let cell = cell else { return }
            
            if playpath2 == playpath {
                cell.progressLabel.text = proText
            } 
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        if self.viewmodel.currentIndexPath.row == indexPath.row {
            return
        }
        self.selectCellWithIndex(index: indexPath.row, immediately: true)
    }
}

